﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using ThinkDotNetBotApiCommon.Weapons;
using ThinkDotNetEngine.Bots.Ammos;

namespace ThinkDotNetEngine.Bots.Weapons
{
    public class CachedWeaponLoader:IWeaponLoader
    {
        readonly private Dictionary<WeaponType, WeaponBase> _cachedWeapons = new Dictionary<WeaponType, WeaponBase>();
        readonly private Dictionary<WeaponType,string>  _mappings=new Dictionary<WeaponType, string>();
        private readonly IAmmoLoader _ammoManager;
        private readonly IAmmoHandler _ammoHandler;

        public CachedWeaponLoader(Game game)
        {
            _ammoManager = (IAmmoLoader)game.Services.GetService(typeof (IAmmoLoader));
            _ammoHandler = (IAmmoHandler) game.Services.GetService(typeof (IAmmoHandler));
            _mappings.Add(WeaponType.Plasma,"weapons\\plasma.txt");
            _mappings.Add(WeaponType.Rocket, "weapons\\rocket.txt");
            _mappings.Add(WeaponType.Missile, "weapons\\missile.txt");
        }

        public WeaponBase Load(TankBot owner,WeaponType weaponType)
        {
            WeaponBase prototype;
            if (_cachedWeapons.ContainsKey(weaponType))
                prototype = _cachedWeapons[weaponType];
            else
            {
                using (Stream stream = File.Open(_mappings[weaponType], FileMode.Open))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(WeaponBase));
                    prototype = (WeaponBase)serializer.Deserialize(stream);
                    _cachedWeapons.Add(weaponType, prototype);
                }
            }
            return (WeaponBase)Activator.CreateInstance(prototype.GetType(), owner,prototype, _ammoManager,_ammoHandler);
        }
        public void Save(string path,WeaponBase weapon)
        {
            using (Stream stream = File.Open(path, FileMode.OpenOrCreate))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(WeaponBase));
                serializer.Serialize(stream, weapon);
            }
        }
    }
}
